<template>
  <div class="container">
    <div class="app-container">
      <el-row style="padding: 20px">
        <el-button size="mini" type="primary" @click="addPermission">添加权限</el-button>
      </el-row>
      <el-table :data="permissionList" :default-expand-all="true" :tree-props="{children: 'children'}"
                border row-key="id" style="width: 100%; padding: 20px">
        <el-table-column header-align="center" label="名称" prop="name" width="200px" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button v-if="row.type === 1" size="mini" @click="btnAddPermission(row)">添加</el-button>
            <el-button size="mini" @click="editPermission(row)">编辑</el-button>
            <el-popconfirm style="margin-left: 10px" title="您确定要删除该数据吗？" @confirm="descPermission(row.id)">
              <template v-slot:reference>
                <el-button size="mini">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <permission-dialog ref="permissionRef" :id.sync="id" :row="row" :show-dialog.sync="showDialog" :title="title"
                       @updatePermission="getPermissionList" />
  </div>
</template>

<script>
import { deletePermissionById, getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import PermissionDialog from '@/views/permission/component/permission-dialog.vue'

export default {
  components: { PermissionDialog },
  data() {
    return {
      permissionList: [],
      showDialog: false,
      title: '',
      id: null,
      row: {}
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transListToTreeData(res, 0)
    },
    // 页面添加权限点
    addPermission() {
      this.showDialog = true
      this.title = '新增权限点'
    },
    // 按钮添加子权限
    btnAddPermission(row) {
      this.row = row
      this.showDialog = true
      this.title = '新增子权限点'
    },
    // 编辑权限
    async editPermission(row) {
      this.showDialog = true
      this.title = '编辑权限点'
      this.id = row.id
      this.$refs.permissionRef.getPermissionDetail()
    },
    // 删除权限点
    async descPermission(id) {
      await deletePermissionById(id)
      this.$message.success('删除权限成功！')
      await this.getPermissionList()
    }
  }
}
</script>

<style scoped>
::v-deep .el-table--border th {
  background-color: #f5f6f8;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
